<template>
  <el-card>
    <div slot="header">
      <h3>维护管理信息</h3>
    </div>
    <div>
      <el-row type="flex" justify="end">
        <el-button
          v-if="tableInfo.dataSource.length > 0"
          type="text"
          size="large"
          @click="handleSubmitData"
          :loading="loading.submit"
          >保存</el-button
        >
        <el-button
          type="text"
          size="large"
          @click="$router.push({ name: 'commodityNotPerfection' })"
        >返回</el-button
        >
      </el-row>
      <el-row>
        <general-render-table
          :tableHeight="0"
          :loading="loading.table"
          :data-source="tableInfo.dataSource"
          :columns="tableInfo.columns"
          @handleChangeCheckBox="handleChangeCheckBox"
          @handleChangeRadio="handleChangeRadio"
        />
      </el-row>
    </div>
  </el-card>
</template>
<script>
import { ApiRequest } from '@api/basePage'
import { mapGetters } from 'vuex';
/* components */
import GeneralRenderTable from '@/pages/commodity/modules/components/generalRenderTable';
/* utils */
import { isResponseSuccess } from '@/utils/bizUtils';
import { getAttributeTypeFn } from '@/pages/commodity/modules/utils';
import { setWarningDialogFunc } from '@/pages/commodity/modules/utils/manageInfoRequireUtils';
export default {
  components: {
    GeneralRenderTable
  },
  data () {
    return {
      loading: {
        table: false, // 表格loading
        submit: false // 提交按钮loading
      },
      tableInfo: {
        dataSource: [], // 表格数据源
        columns: [] // 表格columns
      },
      initManageTableColumns: [ // 表格初始columns
        {
          title: '品类',
          key: 'categoryPath',
          width: 120
        },
        {
          title: 'SPU编码',
          key: 'spuNo',
          width: 120
        },
        {
          title: '商品名称',
          key: 'productNameFinal',
          width: 120
        },
        {
          title: '品牌',
          key: 'brandName',
          width: 120
        }
      ],
      apiObj: {
        commitBasicInfo: {
          url: '/sysback/prepare/commit/allmanaging/saveAllManaging', // 提交接口地址
          type: 'post' // 接口请求类型
        },
      }
    }
  },
  computed: {
    ...mapGetters('permissions/systemBtns', [
      'showBtn'
    ]),
  },
  mounted () {
    this.tableInfo.columns = _.cloneDeep(this.initManageTableColumns);
    this.queryAllManagingAction(this.$route.query.productUuid);
  },
  methods: {
    /* 请求管理信息数据action */
    queryAllManagingAction (productUuid) {
      this.loading.table = true;
      ApiRequest(
        `/sysback/prepare/commit/allmanaging/queryAllManaging?productUuid=${productUuid}`,
        'post',
        false
      ).then(res => {
        this.loading.table = false;
        if (!isResponseSuccess(res)) {
          return false;
        }
        this.initTableDataFunc(res.retData);
      }).catch(() => {
        this.loading.table = false;
      });
    },
    /* 初始化表格数据 */
    initTableDataFunc (retData) {
      this.tableInfo.columns = _.cloneDeep(this.initManageTableColumns);
      this.tableInfo.dataSource = [];
      this.dealTableColumnsThFunc(retData);
    },
    /* 处理表头方法 */
    dealTableColumnsThFunc (retData) {
      const { productUuid, productNameFinal, brandName, categoryPath, spuNo, saleAttrInfo, manageArea } = retData.main;
      let dataResult = {
        productUuid, productNameFinal, brandName, categoryPath, spuNo, saleAttrInfo, manageArea
      }
      const nameList = Object.keys(retData);
      const notForEachName = ['thirdPlatList', 'cityList'];
      const logisticsPackTransportRestrict = ['logistics_pack', 'logistics_transport', 'logistics_restrict'];
      nameList.forEach(nameType => {
        if (!_.isArray(retData[nameType]) || notForEachName.includes(nameType)) { return }
        dataResult[nameType] = []
        retData[nameType].forEach(thItem => {
          if (thItem.attrType === '04') {
            thItem.valueName = thItem.valueName ? _.clone(thItem.valueName).split(/,|，|\s+/) : [] // 以中英文逗号、空格（一个或多个）分割字符串
          }
          dataResult[thItem.attrUuid] = thItem
          dataResult[nameType].push(thItem.attrUuid)
          let column = {
            title: thItem.attrName,
            align: 'center',
            key: thItem.attrUuid,
            type: getAttributeTypeFn(thItem.attrType),
            required: thItem.attrMust === '1' || false,
            disabled: thItem.canEdit === 'N' || false,
            width: thItem.attrType === '04' ? '180' : '140'
          }
          if (logisticsPackTransportRestrict.includes(thItem.attrUuid)) {
            column.placeholder = '物流人员维护';
          }
          this.tableInfo.columns.push(column);
        })
      })
      this.tableInfo.dataSource = [dataResult];
    },
    /* 据归类UUID，查询税类代码taxCateNo、销售税率taxRate */
    getTaxInfoDataAction (data) {
      let { allValueOptions, val } = data
      let target = _.find(allValueOptions, item => { return item.optionHtml === val })
      let uuid = target.optionValue
      let params = { uuid }
      return new Promise((resolve, reject) => {
        this.loading.table = true
        ApiRequest(`/sysback/addsingleproduct/basicinfo/getClassificationByUuid?uuid=${uuid}`, 'post', params).then(res => {
          this.loading.table = false
          if (!isResponseSuccess(res)) {
            resolve(false);
            return false;
          }
          let data = {
            taxCateNo: res.retData.taxCateNo,
            taxRate: res.retData.taxRate
          }
          resolve(data)
        }).catch(() => {
          this.loading.table = false
        })
      })
    },
    /* 处理单选下拉逻辑 */
    handleChangeRadio (data) {
      let { row, val, columnName } = data
      if (columnName === 'tax_classify') { // 如果当前切换的是归类名称字段，就调用归类信息接口
        this.getTaxInfoDataAction({ val, allValueOptions: row.tax_classify.allValueOptions }).then(retData => {
          if (!retData) { return false }
          row.tax_code.valueName = retData.taxCateNo;
          row.tax_rate.valueName = retData.taxRate;
        })
      }
      /* 选择是否季节性商品 */
      if (columnName === 'manage_season_product' && val === '否') {
        row.manage_stock_period.valueName = ''; // 囤货期
        row.manage_soldout_period.valueName = ''; // 下架期
      }
    },
    /* 处理多选下拉逻辑 */
    handleChangeCheckBox (data) {
      let { row, val, columnName } = data;
      const notSaleFlag = val.includes('不销售');
      const notSaleIndex = val.indexOf('不销售');
      if (notSaleFlag) {
        if (val.length === notSaleIndex + 1) {
          row[columnName].valueName = ['不销售'];
        } else {
          row[columnName].valueName.splice(notSaleIndex, 1);
        }
      } else {
        row[columnName].valueName = val;
      }
    },
    /* 重置售卖平台的方法
       保存校验时，当商品四级类的是否限制类为危化品，并且是一级的时候（后端校验），将售卖平台的普通平台的勾选取消)
    */
    resetSalePlatFunc (spuNoList) {
      if (!spuNoList) { return false }
      spuNoList.forEach(spuNo => {
        let index = this.tableInfo.dataSource.findIndex(item => {
          return item.spuNo === spuNo;
        })
        if (index === -1) { return false }
        let normalIndex = this.tableInfo.dataSource[index].marketing_saleplat.valueName.indexOf('普通平台');
        if (normalIndex === -1) { return false }
        this.tableInfo.dataSource[index].marketing_saleplat.valueName.splice(normalIndex, 1);
      })
    },
    /* 获取提交接口所需入参的方法 */
    getSubmitResultsFunc (data) {
      const nameList = ['manageList', 'marketingList', 'taxList', 'logisticsList'];
      let submitResults = {
        productUuid: data.productUuid
      }
      nameList.forEach(nameType => {
        let results = data[nameType].reduce((value, item) => {
          value.push({
            attrUuid: data[item].attrUuid,
            valueInfo: this.getValueInfoFunc(data[item])
          });
          return value;
        }, []);
        submitResults[nameType] = results;
      })
      return submitResults;
    },
    /* 获取入参结构所需valueInfo的方法 */
    getValueInfoFunc (dataSource) {
      if (dataSource.attrType === '01') {
        return dataSource.valueName;
      }
      if (!_.isArray(dataSource.valueName)) {
        return this.getOptionValueFunc(dataSource, dataSource.valueName);
      }
      let valueInfoList = dataSource.valueName.reduce((value, item) => {
        value.push(this.getOptionValueFunc(dataSource, item));
        return value;
      }, []);
      return valueInfoList.join(',');
    },
    /* 获取下拉optionValue的方法 */
    getOptionValueFunc (dataSource, target) {
      let result = dataSource.allValueOptions.find(option => {
        return option.optionHtml === target;
      });
      if (!result) {
        return null;
      }
      return result.optionValue;
    },
    /* 提交数据事件 */
    handleSubmitData () {
      let submitResults = this.getSubmitResultsFunc(this.tableInfo.dataSource[0]);
      let { url, type } = this.apiObj.commitBasicInfo;
      this.loading.submit = true;
      ApiRequest(url, type, submitResults, false).then(res => {
        this.loading.submit = false;
        if (!isResponseSuccess(res)) {
          setWarningDialogFunc(this, res, this.resetSalePlatFunc);
          return false;
        }
        this.$message.success('提交成功');
        this.tableInfo.dataSource = [];
        this.$router.push({ name: 'commodityNotPerfection' }) // 跳转待准入页面
      }).catch(() => {
        this.loading.submit = false;
      })
    }
  }
}
</script>
